package com.xm.settlement.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xm.settlement.commons.base.ApiSQLException;
import com.xm.settlement.commons.utils.PageInfo;
import com.xm.settlement.mapper.ScorePoolMapper;
import com.xm.settlement.model.ScorePool;
import com.xm.settlement.model.UserExpansion;
import com.xm.settlement.service.ScorePoolService;
import com.xm.settlement.service.UserExpansionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2017/4/21.
 */
@Service
public class ScorePoolServiceImpl extends SuperServiceImpl<ScorePoolMapper,ScorePool>  implements ScorePoolService{

    @Autowired
    private  ScorePoolMapper scorePoolMapper;
    @Autowired
    private UserExpansionService userExpansionService;

    @Override
    public void selectDataGrid(PageInfo pageInfo) {
        Page<ScorePool> page = new Page<ScorePool>(pageInfo.getNowpage(), pageInfo.getSize());
        List<ScorePool> list = scorePoolMapper.selectScorePoolList(page);
        pageInfo.setRows(list);
        pageInfo.setTotal(page.getTotal());
        /**--------------------
         *   全部的增值点
         * --------------------*/
        UserExpansion userExpansion = new UserExpansion();
        Long scorePool = userExpansionService.selectSum(userExpansion).longValue();
        for (ScorePool s:list){
                s.setSumScore(scorePool);
        }
    }

    /***----------------
     *  均分奖池
     *------------------ */
    @Override
    public void insertAvgScore(Double awards) throws ApiSQLException {

        UserExpansion userExpansion = new UserExpansion();
        Long increment = userExpansionService.selectSum(userExpansion).longValue();

        /**
         *  均分金额
         * */
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.orderBy(" publishTime",false);
        List<ScorePool> list =  scorePoolMapper.selectList(entityWrapper);
        ScorePool scorePool = list.get(0);
        if(scorePool.getScore() <awards ){
                throw new ApiSQLException(1102,"奖金池少于当前金额");
        }
        double avgScore = scorePool.getScore() * 1.00/increment ;
        /**
         * -------------
         * 奖金增长
         * -----------*/
        userExpansionService.updateAvgScore(avgScore);

        /***--------------
         *  当累计奖金达到 1000时扣除增值点
         * ---------------***/
        Integer mut = 1000 ;
        userExpansionService.reduceIncrement(mut);

        /***--------------
         *  修改现金池总数金额
         * ---------------***/
        scorePool.setScore( scorePool.getScore() - awards);
        scorePoolMapper.updateById(scorePool);

    }
}
